/*
 * grunt-cli
 * http://gruntjs.com/
 *
 * Copyright (c) 2012 Tyler Kellen, contributors
 * Licensed under the MIT license.
 * https://github.com/gruntjs/grunt-init/blob/master/LICENSE-MIT
 */

'use strict';
module.exports = function(grunt) {
    //http://stackoverflow.com/questions/5827612/node-js-fs-readdir-recursive-directory-search
    var fs = require('fs');
    var path = require('path');
    var reg =  new RegExp("(^[a-zA-Z]+(\w)*)(.js)$");
    var combileModules = [];
    function retrieve(dir) {
        var fileArry = [];
        var list = fs.readdirSync(dir)
        var num = list.length;
        if (!num){
          console.log('no file in' + dir);
          return flase
        }
        for(var i = 0; i<num;i++){
          var filePath = path.resolve(dir, list[i]);
          if(fs.statSync(filePath).isFile()){
                fileArry.push(list[i])
            }
        }
        return fileArry;
    };
    function filterFiles(list,relaDir){
        var fileArry = [];
        var relaPath = relaDir ? relaDir : '';
        for(var i = 0;i<list.length;i++){
            if(reg.test(list[i])){
                var joinPath = relaPath + list[i].replace(reg,"$1");
              fileArry.push(joinPath);
            }
        }
        return fileArry;
    }
    function buildModules(jsDir,libDir){
        combileModules.length = 0
        var jsPath = jsDir ? jsDir : './js';
        var libPath = libDir ? libDir : './lib';

        var find = retrieve(libPath);
        var libFiles = find ? filterFiles(find,'./') : [''];
        find = retrieve(jsPath);
        var jsFiles = find ? filterFiles(find) : false;
        if(!jsFiles) return
        for(var i=0;i<jsFiles.length;i++){
            var modObj = {
                name: jsFiles[i]
                , exclude: libFiles
            };
            combileModules.push(modObj)
        }
        console.log(combileModules)
    }
  // Project configuration.
    grunt.initConfig({// 配置任务
        pkg:grunt.file.readJSON('package.json')
        //清除文件
        , clean:{
            js:['dest/js']
            , html:['dest/html']
            , css:['dest/css']
            , lib:['dest/lib/*']
            , img:['dest/images/*']
            , build:['./build']
        }
        , requirejs: {
            target: {
                options: {
                    baseUrl: './build/js'
                    , modules: combileModules
                    , mainConfigFile: './build/js/_config.js'
                    , dir:'./dest/js'
                    , optimize: 'uglify' //uglify
                    , removeCombined: true
                }
            }
        }
        , includereplace: {
            html: {
                src: ['./html/**/*.html','!./html/**/_*.html']
                , dest: './dest/'
            }
            , dev: {
                src: ['./dest/js/**/*.js']
                , dest: './'  //放在当前目录，即./dest/js
            }
            , fac: {
                src: ['./build/js/**/*.js']
                , dest: './'  //放在当前目录，即./dest/js
            }
        }
        //less 构建
        , less: {
            dev: {
                files: [{
                    expand: true
                    , cwd: './less'
                    , src: ['**/*.less','!**/_*.less']
                    , dest: './dest/css'
                    , ext: '.css'
                }]
            }
            ,fac: {
                options:{
                    compress: true
                    , ieCompat: true
                }
                , files: [{
                    expand: true
                    , cwd: './less'
                    , src: ['**/*.less','!**/_*.less']
                    , dest: './dest/css'
                    , ext: '.css'
                }]
            }
        }
        , copy: {
            lib: {
                expand: true
                , cwd:'./lib'
                , src: '**'
                , dest: './dest/lib'
            }
            , img:{
                expand: true
                , cwd: './images'
                , src: '**'
                , dest: './dest/images'
            }
            , js:{
                expand: true
                , cwd: './js'
                , src: '**/*.js'
                , dest: './dest/js'
            }
            , buildjs:{
                expand: true
                , cwd: './js'
                , src: '**/*.js'
                , dest: './build/js'
            }
            , buildlib: {
                expand: true
                , cwd:'./lib'
                , src: '**'
                , dest: './build/lib'
            }
        }
        //文件监控
        , watch:{
            js:{
                files:['**/*.js']
                , tasks:['clean:js','copy:js','includereplace:dev']
                , options:{
                    cwd:'./js'
                }
            }
            ,less:{
                files:['**/*.less']
                , tasks:['clean:css','less:dev']
                , options:{
                    cwd:'./less'
                }
            }
            , html:{
                files:['**/*.html']
                , tasks:['clean:html','includereplace:html']
                , options:{
                    cwd:'./html'
                }
            }
            , copylib:{
                files:['**/*']
                , tasks:['clean:lib','copy:lib']
                , options:{
                    cwd:'./lib'
                }
            }
            ,copyimg:{
                files:['**/*']
                , tasks:['clean:img','copy:img']
                , options:{
                    cwd:'./images'
                }
            }
            ,configFiles: {
                files: [ 'Gruntfile.js']
                , options: {
                    reload: true
                }
            }
        }
        , build:buildModules()
        , develop:{
            clean:['clean']
            , copy:['copy:lib','copy:img','copy:js']
            , replace:['includereplace:html','includereplace:dev']
            , less:['less:dev']
        }
        , factory:{
            first: ['clean:img','copy:img']
            , second: ['clean:lib','copy:lib']
            , third: ['clean:html','includereplace:html']
            , fourth: ['clean:css','less:fac']
            , fifth: ['clean:build','copy:buildlib','copy:buildjs']
            , sixth: ['includereplace:fac','build']
            , end:['clean:js','requirejs']
        }
    });
    // These plugins provide necessary tasks.
    // grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-contrib-requirejs');
    grunt.loadNpmTasks('grunt-include-replace');
    grunt.loadNpmTasks('grunt-contrib-copy');

    grunt.task.registerTask('build','create moudules option',function(){})
    grunt.task.registerMultiTask('factory','factory mode',function(){
        grunt.task.run(this.data)
    })
    grunt.task.registerMultiTask('develop','factory mode',function(){
        grunt.task.run(this.data)
    })
    // grunt.registerTask('factory','factory files',function(){
    //     grunt.task.run(['clean:img','copy:img'])
    //     grunt.task.run(['clean:lib','copy:lib'])
    //     grunt.task.run(['clean:html','includereplace:html'])
    //     grunt.task.run(['clean:css','less:fac'])
    //     grunt.task.run(['clean:js','copy:js','','build','requirejs'])
    //     // grunt.task.run(['clean','includereplace','copy:img','copy:lib','build','requirejs','less:factory'])
    // })
    // grunt.registerTask('default', ['clean','copy:img','copy:lib','copy:js','includereplace','less:dev']);
    //,'watch'
    grunt.registerTask('default',['develop','watch'])
}